import { setActiveEvent,activeEventisEmpty } from "../main";
class Square {
    name;
    size;//尺寸
    //位置
    x;
    y;
    //切割的图片位置
    positionImg;
    constructor(size,x,y,positionImg = {
        sx:0,
        sy:0,
        sWidth:0,
        sHeight:0
    },name) {
        this.size = size;
        this.x = x;
        this.y = y;
        this.positionImg = positionImg;
        this.name = name;
    }
    //绘制
    draw(ctx,img) {
        ctx.save();
        let {sx,sy,sWidth,sHeight} = this.positionImg
        ctx.drawImage(img,sx,sy,sWidth,sHeight,this.x,this.y,this.size,this.size)
        ctx.restore();
    }
    //点击事件
    click() {
        return this
    }
    //移动
    move(orientation='up') {
        switch(orientation) {
            case 'up':
                this.moveTo(this.x,this.y-this.size)
                break;
            case 'down':
                this.moveTo(this.x,this.y+this.size)
                break;
            case 'left':
                this.moveTo(this.x-this.size,this.y)
                break;
            case 'right':
                this.moveTo(this.x+this.size,this.y)
                break;
        }
    }
    //移动到目标位置,
    moveTo(targetX,targetY,moveTime=4) {
        let xStep = (targetX - this.x) / moveTime
        let yStep = (targetY - this.y) / moveTime
        setActiveEvent(()=>{
            this.x+=xStep
            this.y+=yStep
            if(xStep<0 && this.x<targetX){
                this.x=targetX
                this.y=targetY
                setActiveEvent(null)
            }
            if(xStep>0 && this.x>targetX){
                this.x=targetX
                this.y=targetY
                setActiveEvent(null)
            }
            if(yStep<0 && this.y<targetY){
                this.x=targetX
                this.y=targetY
                setActiveEvent(null)
            }
            if(yStep>0 && this.y>targetY){
                this.x=targetX
                this.y=targetY
                setActiveEvent(null)
            }
        })
    }
}
export default Square;